import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'
// import { reject, resolve } from 'core-js/fn/promise'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      const token = getToken()
      config.headers['Authorization'] = `Bearer ${token}`
    }
    // console.log('config', config)
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 10000) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      if (!res.success) {
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
        // if (res.code === 10002) {
        //   console.log('222', 222)
        //   router.push('/login')
        // }
      }
      return res
    }
  },
  async(error) => {
    console.log('err' + error) // for debug
    if (error.response.status === 401) {
      // console.log('error11', error) 这里打印没有error.response.status
      // 这里的响应为什么是 error ,不应该请求成功了吗？
      console.log('222', 222)
      router.push('/login')
    }
    await store.dispatch('user/logout')
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 封装属于自己的 get post put delete 方法
export default service

// 这是get
export const get = (url, params) => {
  return service({
    method: 'GET',
    url,
    params
  })
}

export const post = (url, data) => {
  return service({
    method: 'POST',
    url,
    data
  })
}

export const put = (url, data) => {
  return service({
    method: 'PUT',
    url,
    data
  })
}

export const delet = (url, params) => {
  return service({
    method: 'DELETE',
    url,
    params
  })
}
